<?php

namespace app\store\controller;

use app\common\model\Setting;
use app\common\enum\AppointmentStatus;
use app\store\model\appointment\Offline as OfflineModel;
use app\store\model\appointment\Order ;
use app\store\model\appointment\Service;
use app\store\model\appointment\Time as TimeModel;
use app\store\model\appointment\Type as TypeModel;
use app\common\service\Order as OrderService;
use app\store\model\server\User as UserModel;
use app\api\model\WxMessage;

use think\Db;

/**
 * 预约管理
 * Class Order
 * @package app\store\controller
 */
class Offline extends Controller
{
    /**
     * 全部预约订单列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function all_list($dataType = 'all')
    {
        $model = new OfflineModel;
        $list = $model->getList($this->request->param());

        $userModel = new UserModel;
        $service_list = $userModel->getList();
        return $this->fetch('index', compact(  'dataType', 'service_list', 'list'));
    }

    public function add()
    {
        $model = new OfflineModel;
        if (!$this->request->isAjax()) {
            $order_id = OrderService::createOrderNo();

            $userModel = new UserModel;
            $service_list = $userModel->getList();
            $status_list = AppointmentStatus::data();

            $timeModel = new TimeModel;
            $time_list = $timeModel->getList();

            $typeModel = new TypeModel;
            $type_list = $typeModel->getList();
            if(empty($service_list[0]['wxapp_id'])){
                $wxapp_id = null;
            }else{
                $wxapp_id = $service_list[0]['wxapp_id'];
            }
            $config = Setting::getItem('store',$wxapp_id);
            $laiyuans = explode('、',$config['laiyuan']);
            return $this->fetch('add',
                array_merge(compact('order_id', 'status_list', 'service_list', 'time_list', 'type_list','laiyuans')));
        }
        // 新增记录

        $send_sms = $this->postData('send_sms');
        $data = $this->postData('model');
        if ($model->add($this->postData('model'))) {

            $order = Db::name("appointment_order")->where(array("service_id"=>$data['service_id']))->order(['id' => 'desc'])->find();

            if($send_sms[0] == 1){
                //YPP 推送短信
                $server = Db::name("server_user")->where(array("user_id"=>$data['service_id']))->find();
                $appointment = Db::name("appointment_type")->where(array("type_id"=>$data['type_id']))->find();
                $message = [
                    'mobile' => $data['user_phone'],
                    'client_name' => $data['user_name'],
                    'server_user_name' => $server['real_name'],
                    'server_phone' => $server['mobile'],
                    'server_name' => $appointment['name']
                ];
                //推送预约信息
                $message_status = WxMessage::sendMessage(13, $message);
            }
            //$today = strtotime(date("Y-m-d",time()));
            $appointment_date = strtotime($data['appointment_date']);

            $lastorder = Db::name("appointment_order")->where(array("service_id"=>$data['service_id'],"type_id"=>$data['type_id'],"appointment_date"=>$appointment_date))->order(['order_target' => 'desc'])->find();

            if($lastorder && $lastorder['order_target']>0){
                $order_target = $lastorder['order_target']+1;
            }else{
                $order_target = 1;
            }

            Db::name("appointment_order")->where(array("id"=>$order['id']))->update(['order_target'=>$order_target]);


            return $this->renderSuccess('添加成功', url('offline/all_list'));
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }

    /**
     * 预约编辑
     * @return array|bool|mixed
     */
    public function edit()
    {
        $order_id = input('order_id');
        // 订单列表
        $offlineModel = new OfflineModel;
        // 商品详情
        $model = $offlineModel->where('order_id', $order_id)->find();
        if (!$this->request->isAjax()) {
            $userModel = new UserModel;
            $service_list = $userModel->getList();
            $status_list = AppointmentStatus::data();

            $timeModel = new TimeModel;
            $time_list = $timeModel->getList(['type_id' => $model['type_id']]);

            foreach($time_list as $k=>$v){
                $orders = Db::name("appointment_order")->where('find_in_set(:time_id,time_id)',['time_id'=>$v['time_id']])->where(array('service_id'=>$model['service_id'],'appointment_date'=>$model['appointment_date']))->select()->toArray();
                $str = "";
                foreach($orders as $key=>$val){
                    if($val['order_target'] >0){
                        $str .= $val['order_target'].",";
                    }
                }
                $time_list[$k]['target'] = $str;
            }



            $typeModel = new TypeModel;
            $type_list = $typeModel->getList($model['type_id']);
            $model['time_id'] = explode(',',$model['time_id']);
            $order = Db("order")->where('order_id', $model['user_order_id'])->field('order_no,total_price,wxapp_id')->find();
            if (!empty($order)) {
                $model['money'] = $order['total_price'];
            }

            $model['use_time'] = Db("appointment_service")->where('order_id', $model['id'])->value('use_time');

            if ($model['user_order_id'] > 0) {
                $model['user_order_name'] = $order['order_no'] . '/' . $order['total_price'];
            } else {
                $model['user_order_name'] = '';
            }

            $config = Setting::getItem('store',$model['wxapp_id']);
            $laiyuans = explode('、',$config['laiyuan']);

            return $this->fetch(
                'edit',
                array_merge(compact('status_list', 'service_list', 'model', 'time_list', 'type_list', 'laiyuans'))
            );
        }
        $orderModel = new \app\store\model\appointment\Order();
        // 更新记录
        $data = $this->postData('model');
        $service_id = $data['service_id'];
        $order =  $orderModel->where(array("order_id"=>$order_id))->find();
        if ($model->edit($this->postData('model'))) {
            //YPP 改变服务人员
            if($order['service_id'] != $service_id){
                $appointment_date = strtotime($data['appointment_date']);
                //$today = strtotime(date("Y-m-d",time()));
                $lastorder =  $orderModel->where(array("service_id"=>$data['service_id'],"type_id"=>$data['type_id'],"appointment_date"=>$appointment_date))->order(['order_target' => 'desc'])->find();
                if($lastorder && $lastorder['order_target']>0){
                    $data['order_target'] = $lastorder['order_target']+1;
                }else{
                    $data['order_target'] = 1;
                }
            }

            unset($data['money']);
            unset($data['use_time']);
            $data['appointment_date'] = strtotime($data['appointment_date']);
            $res = $orderModel
                ->where(array("order_id"=>$order_id))
                ->update($data);
            return $this->renderSuccess('更新成功', url('offline/all_list'));
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

    /**
     * 软删除
     * @param $time_id
     * @return array|bool
     */
    public function delete($order_id)
    {
        $model = OfflineModel::detail($order_id);
        if (!$model->setDelete()) {
            return $this->renderError($model->getError() ?: '删除失败');
        }
        return $this->renderSuccess('删除成功');
    }

}
